package com.demo.starter.config;

import com.demo.starter.Application;
import com.demo.starter.interceptor.WebMvcAttributeInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
@ComponentScan(basePackageClasses = Application.class, useDefaultFilters = true)
public class AppConfig extends WebMvcConfigurationSupport {

    /**
     * 配置拦截器
     * @param registry
     */
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        // 添加公共 attribute 的拦截器
        registry.addInterceptor(webMvcAttributeInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/api/**", "/ajax/**", "/error");
        super.addInterceptors(registry);
    }

    /**
     * 配置静态资源路径 <i>必须</i>
     * <pre>配置 Interceptor 后，必须配此项，否则静态资源 404</pre>
     * @param registry
     */
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/")
                .addResourceLocations("classpath:/templates/");
    }

    /**
     * 以注解的方式获取Interceptor实例，确保实例中的Service正常实例化
     * @return
     */
    @Bean
    public WebMvcAttributeInterceptor webMvcAttributeInterceptor() {
        return new WebMvcAttributeInterceptor();
    }

}
